package cn.com.wxd.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.common.CharUtil;
import cn.com.wxd.web.listener.WebAppRootListener;

/**
 * Title:RequestUtil.java
 * Description:cn.com.wxd.util.action
 * 
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2015-10-27 上午11:27:25
 *
 * @author WangXuDong
 * @version 1.0
 */
public class RequestUtil {
	private static final Logger log = LoggerFactory.getLogger(RequestUtil.class);
	/**
	 * 获取客户端IP
	 * @param request request
	 * @return IP
	 */
	public static String getRemortIP(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if(!CharUtil.isEmpty(ip)&&!"unknown".equalsIgnoreCase(ip))
		{
			return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if(!CharUtil.isEmpty(ip)&& !"unknown".equalsIgnoreCase(ip))
		{
			int index = ip.indexOf(',');
			if(index != -1){
				return ip.substring(0, index);
			}else{
				return ip;
			}
		}
		return request.getRemoteAddr();
	}
	/**
	 * 获取请求参数
	 * @param request request
	 * @param param 参数名称
	 * @return 参数值
	 */
	public static String getParameter(HttpServletRequest request, String param)
	{
		String value = request.getParameter(param);
		if (value == null)
			value = "";
		value = value.replaceAll("<", "&lt;");
		value = value.replaceAll(">", "&gt;");
		value = value.replaceAll("&", "&amp;");
		value = value.replaceAll("#", "");
		value = value.replaceAll("\"", "&quot;");
		value = value.replaceAll("'", "");
		value = value.replaceAll("[(]", "");
		value = value.replaceAll("[)]", "");

		return value;
	}
	/**
	 * 获取项目的根目录根据类的相对路径获取
	 * @return  真实路径（绝对路径）
	 */
	public static String getRealPath(){
		String path = WebAppRootListener.getRealPath();
		if(path == null || path.equals("")){
			path = RequestUtil.class.getClassLoader().getResource("").getPath();
			if(path.contains("classes") || path.contains("/WEB-INF") || path.contains("/lib")){
				try {
					path=URLDecoder.decode(path,"utf-8");
				} catch (UnsupportedEncodingException e) {
					log.error(e.getMessage(),e);
				}
				String rootPath;
				if(path.startsWith("/")){
					rootPath = path.substring(1, path.indexOf("/WEB-INF/"));
				}else{
					rootPath = path.substring(0, path.indexOf("/WEB-INF/"));
				}
				path = rootPath;
			}
		}
		return path;
	}
	/**
	 * 获取项目的根目录根据应用的上下文
	 * @param servletContext
	 * @return  真实路径（绝对路径）
	 */
	public static String getRealPath(ServletContext servletContext){
		return servletContext.getRealPath("/");
	}
	/**
	 * 设置cookie
	 * @param response
	 * @param name  cookie名字
	 * @param value cookie值
	 * @param maxAge cookie生命周期  以秒为单位
	 */
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){
		Cookie cookie = new Cookie(name,value);
		cookie.setPath("/");
		if(maxAge>0)  cookie.setMaxAge(maxAge);
		response.addCookie(cookie);
	}
	/**
	 * 根据名字获取cookie
	 * @param request
	 * @param name cookie名字
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request,String name){
		Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
		Cookie[] cookies = request.getCookies();
		if(null!=cookies){
			for(Cookie cookie : cookies){
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		if(cookieMap.containsKey(name)){
			Cookie cookie = (Cookie)cookieMap.get(name);
			return cookie;
		}else{
			return null;
		}   
	}
	/**
	 * 获取当前域名
	 * @param request
	 * @return
	 */
	public static String getDomainName(HttpServletRequest request){
		StringBuffer url = request.getRequestURL();  
		String tempContextUrl = url.delete(url.length() - request.getRequestURI()
				.length(), url.length()).append("/").toString();
		return tempContextUrl;
	}
	/**
	 * 获取含有项目名称的域名
	 * @param request
	 * @return
	 */
	public static String getDomainNameandProjectName(HttpServletRequest request){
		StringBuffer url = request.getRequestURL();  
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length())
				.append(request.getContextPath()).append("/").toString();
		return tempContextUrl;
	}

}
